package com.zoctan.api.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zoctan.api.common.util.AssertUtils;
import com.zoctan.api.dto.RoleWithPermission;
import com.zoctan.api.dto.RoleWithResource;
import com.zoctan.api.entity.Role;
import com.zoctan.api.service.RoleService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.security.Principal;
import java.util.List;

/**
 * @author Zoctan
 * @date 2018/06/09
 */
@RestController
@RequestMapping("/role")
public class RoleController {
  @Resource private RoleService roleService;

  @PreAuthorize("hasAuthority('role:add')")
  @PostMapping
  public void add(@RequestBody final RoleWithPermission role, final Principal principal) {
    this.roleService.save(role);
  }

  @PreAuthorize("hasAuthority('role:delete')")
  @DeleteMapping("/{id}")
  public void delete(@PathVariable final Long id, final Principal principal) {
    final Role dbRole = this.roleService.getById(id);
    AssertUtils.notNull(dbRole, "角色不存在");
    this.roleService.deleteById(id);
  }

  @PreAuthorize("hasAuthority('role:update')")
  @PutMapping
  public void update(@RequestBody final RoleWithPermission role, final Principal principal) {
    final Role dbRole = this.roleService.getById(role.getId());
    AssertUtils.notNull(dbRole, "角色不存在");
    this.roleService.update(role);
  }

  @PreAuthorize("hasAuthority('role:list')")
  @GetMapping("/permission")
  public PageInfo<RoleWithResource> listWithPermission(
      @RequestParam(defaultValue = "0") final Integer page,
      @RequestParam(defaultValue = "0") final Integer size) {
    PageHelper.startPage(page, size);
    final List<RoleWithResource> list = this.roleService.listRoleWithPermission();
    return new PageInfo<>(list);
  }

  @GetMapping
  public PageInfo<Role> list(
      @RequestParam(defaultValue = "0") final Integer page,
      @RequestParam(defaultValue = "0") final Integer size) {
    PageHelper.startPage(page, size);
    final List<Role> list = this.roleService.listAll();
    return new PageInfo<>(list);
  }
}
